package com.huatai.bi.handler.datasource;

import com.huatai.bi.constant.SystemConstant;
import com.huatai.bi.entity.DatasourceEntity;
import com.huatai.bi.handler.DatasourceHandler;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

@Log4j2
public class MysqlDatasource extends DatasourceHandler {

    public MysqlDatasource(DatasourceEntity entity){
        super(entity);
    }

    @Override
    protected String jdbcUrl(DatasourceEntity entity) {
        StringBuffer url = new StringBuffer(entity.getJdbcUrl());
        //url编码
        if(StringUtils.isNoneBlank(entity.getEncode()) && url.indexOf("characterEncoding") < 0){
            if(url.indexOf("?")<0){
                url.append("?");
            }else{
                url.append("&");
            }
            url.append("characterEncoding=").append(entity.getEncode());
        }
        return url.toString();
    }

    @Override
    public void sqlInit(){
        switch (type){
            case SystemConstant.JDBC_SQL_TYPE_TABLE:
                sql = "SELECT table_catalog,table_schema,table_name,table_comment,create_time FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA  = (select database())";
                return;
            case SystemConstant.JDBC_SQL_TYPE_COLUMN:
                sql = "SELECT table_name,column_name,column_comment,column_type,ordinal_position,column_default,is_nullable FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA  = (select database())";
                return;
            case SystemConstant.JDBC_SQL_TYPE_VERSION:
                sql = "select version()";
                return;
            case SystemConstant.JDBC_SQL_TYPE_SQL_PAGE:

                sql = "select t.* from ("+sql+") t limit "+pageStartIndex+","+pageSize;
                return;
            case SystemConstant.JDBC_SQL_TYPE_SQL_PAGE_COUNT:
                sql = "select count(1) from ("+sql+") t";
                return;
            default:return;
        }
    }
}
